import { TreeSelect, Radio, Col, Row, Statistic, Divider, Select } from 'antd';
import { FormattedMessage, connect, formatMessage, Dispatch } from 'umi';
import React, { useState, useEffect } from 'react';
import ECharts from 'echarts-for-react';
import * as echarts from 'echarts';
const { Option } = Select;
import { GridContent } from '@ant-design/pro-layout';
import cloneDeep from 'lodash.clonedeep';

import styles from './style.less';
import { queryEnergyAnalysis, queryEnergyAnalysisByType,queryEnergyAnalysisenergyNum } from '@/services/energyAnalysis';
import { numberConversion } from '@/utils/utils';
import { queryAreaTree } from '@/services/area';
import { queryDeviceList } from '@/services/device';

const Survey: React.FC = () => {
  const [energyNum, setenergyNum] = useState([]);
  const [qushiOption, setQushiOption] = useState();
  const [option, setOption] = useState();
  const [peakValue, setPeakValue] = useState({});
  const [areaTreeData, setAreaTreeData] = useState<API.TreeNodeItem[]>([]);
  const [areaId, setAreaId] = useState<number>();
  const [deviceId, setDeviceId] = useState<number>(80000115);
  const [deviceList, setDeviceList] = useState<API.DeviceItem[]>([]);

  useEffect(() => {
    setAnalysisData(deviceId, areaId, 1);
  }, []);

  const setAnalysisData = async (dId, aId, typeId) => {
   queryEnergyAnalysis({ areaId: aId, deviceId: dId, typeId }).then(function(analysis){
    setPeakValue(analysis.peakValue);
    let new_data = { ...DEFAULT_OPTION };
    new_data.xAxis.data = analysis.phaseTime;
    new_data.series[0].data = analysis.yestodayNum;
    new_data.series[1].data = analysis.todayNum;
    setOption(new_data);
    })

   queryEnergyAnalysisenergyNum({ areaId: aId, deviceId: dId, typeId }).then(function(energyNum){
      energyNum.dayPercentage = getPercentage(energyNum.today_num || 0, energyNum.yestoday_num || 0);
      energyNum.dayDifference = energyNum.today_num || 0 - energyNum.yestoday_num || 0;
      energyNum.dayDifference =
        ((energyNum.dayDifference || 0) > 0 ? '+' : '') + numberConversion(energyNum.dayDifference || 0);
      energyNum.monthPercentage = getPercentage(
        energyNum.current_mouth_num || 0,
        energyNum.last_mouth_num || 0,
      );
      energyNum.monthDifference = energyNum.current_mouth_num || 0 - energyNum.last_mouth_num || 0;
      energyNum.monthDifference =
        ((energyNum.monthDifference || 0) > 0 ? '+' : '') + numberConversion( energyNum.monthDifference || 0);
      energyNum.yearPercentage = getPercentage(
        energyNum.this_year_num || 0,
        energyNum.last_year_num || 0,
      );
      energyNum.yearDifference = energyNum.this_year_num || 0 - energyNum.last_year_num || 0;
      energyNum.yearDifference =
        ((energyNum.yearDifference || 0) > 0 ? '+' : '') + numberConversion( energyNum.yearDifference || 0);
  
      setenergyNum(energyNum);
  })

  

    queryEnergyAnalysisByType({
      typeId,
      areaId: aId,
      deviceId: dId,
      energyNum,
    }).then(function(energyNum){
      changeTypeData(energyNum);
    })
  
  

    let trees = await queryAreaTree();
    setAreaTreeData(trees);

    let devices = await queryDeviceList({ areaId: aId, deviceTypeId: 3 });
    setDeviceList(devices);
  };

  const changeTypeData = async (analysis: any) => {
    let new_data = { ...QUSHI_OPTION };
    new_data.xAxis.data = analysis.trendTime;
    new_data.series[0].data = analysis.trendData;

    setQushiOption(new_data);
  };

  const changeDeviceList = async (e) => {
    setDeviceId(null);
    setAnalysisData(deviceId, e, type);
    // let devices = await queryDeviceList({areaId:e,type:1});
    // console.log(devices)
    //  setDeviceList(devices);
  };

  const changeDevice = async (e) => {
    setDeviceId(e);

    setAnalysisData(e, areaId, type);
  };

  async function handleSizeChange(e) {
    setType(e.target.value);
    const analysis = await queryEnergyAnalysisByType({
      typeId: e.target.value,
      areaId,
      deviceId,
      energyNum,
    });
    changeTypeData(analysis);
  }

  const getPercentage = (num1, num2) => {
    if (num1 == 0 && num2 == 0) {
      return '--';
    }
    var percentage = '+--';
    // num2= num2==0?1:num2;
    if (num2 == 0) {
      num2 = 1;
      num1++;
      percentage =  '+100%';
    }else{
      percentage = ((num1 - num2) / num2) * 100;
      percentage = percentage.toFixed(2);
      percentage = (num1 > num2 ? '+' : '') + percentage + '%';
    }

    return percentage;
  };

  const DEFAULT_OPTION = {
    color: ['#27d08a', '#59cfff'],
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis',
    },

    legend: {
      left: 'right',
      itemWidth: 10,
      itemHeight: 10,
      data: ['今日', '昨日'],
      itemStyle: {
        borderRadius: '10px',
      },
      textStyle: {
        color: 'white',
      },
    },
    grid: {
      // left: 50,
      // right: '30',
      // bottom: '30',
    },
    xAxis: {
      type: 'category',
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#fff',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
      // boundaryGap: true,
      data: [  ],
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#fff',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    dataZoom: [
    ],
    series: [
      {
        name: '昨日',
        type: 'line',
        stack: '总量',
        smooth: true,
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' },
          ],
        },
        markLine: {
          data: [{ type: 'average', name: '平均值' }],
          label: {
            color: '#fff',
            position:'insideEndTop',
          },
        
        },
        data: [  ],
      },
      {
        name: '今日',
        type: 'line',
        stack: '总量',
        smooth: false,
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' },
          ],
        },
        markLine: {
          data: [{ type: 'average', name: '平均值' }],
          label: {
            color: '#fff',
          },
        },
        data: [ ],
      },
    ],
  };

  var dataAxis = [];
  var data = [];
  const QUSHI_OPTION = {
    tooltip: {
      trigger: 'axis',
    },
    title: {},
    xAxis: {
      type: 'category',
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#fff',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
      data: dataAxis,
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#fff',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    dataZoom: [
      {
        type: 'inside',
      },
    ],
    grid: {
      // left: 50,
      // right: 50,
      // bottom: 30,
    },
    series: [
      {
        type: 'bar',
        name: '负荷趋势',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' },
          ]),
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' },
          ],
        },
        markLine: {
          data: [{ type: 'average', name: '平均值' }],
          label: {
            color: '#fff',
          },
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' },
            ]),
          },
        },
        data: data,
      },
    ],
  };

  // 设备
  const OptionData = (list) => {
    if (!list || list.length < 1) {
      return (
        <Option key={''} value={''}>
          没有找到选项
        </Option>
      );
    }
    return list.map((item) => (
      <Option key={item.deviceId} value={item.deviceId}>
        {item.deviceName}
      </Option>
    ));
  };

  const [type, setType] = useState<string>('1');

  return (
    <div className={styles.main}>
      <Row gutter={24}>
        <div className={styles.inputBg}>
          <TreeSelect
            onChange={(e) => {
              setAreaId(e);
              changeDeviceList(e);
            }}
            style={{ width: '260px', marginLeft: '10px' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={areaTreeData}
            placeholder="请选择所在区域"
            treeDefaultExpandAll
          />
        </div>

        <div className={styles.inputBg}>
          <Select
            bordered={false}
            value={deviceId}
            onChange={(e) => {
              changeDevice(e);
            }}
            style={{ width: 'auto', minWidth: 120 }}
            placeholder="请选择设备"
            dropdownStyle={{ background: 'rgb(20, 49, 115)' }}
          >
            {OptionData(deviceList)}
          </Select>
        </div>
      </Row>
      <Divider dashed />
      <Row gutter={[0, 24]}>
        <Col
          xl={18}
          lg={18}
          md={24}
          sm={24}
          xs={24}
          style={{ marginBottom: 24 }}
          className={[styles.servuychart, styles.box].join(' ')}
        >
          <Row className={styles.sinTitle}>
            <span className={styles.signLine}></span>
            <span>日用电平均负荷曲线</span>
          </Row>
          {option != null ? (
            <ECharts option={option} style={{ height: 300, width: '100%' }} />
          ) : null}
        </Col>
        <Col
          xl={6}
          lg={6}
          md={24}
          sm={24}
          xs={24}
          style={{ marginBottom: 24 }}
          className={[styles.energyTR, styles.box].join(' ')}
        >
          <Row className={styles.sinTitle}>
            <span className={styles.signLine}></span>
            <span>用电峰值</span>
          </Row>
          <Row className={styles.content}>
            <Row className={styles.energyBox}>
              <Row className={styles.row1}>{numberConversion(peakValue?.todayMax) }</Row>
              <Row className={styles.row2}>
                <p> {peakValue?.todayMaxTime || '--'}</p>
              </Row>
              <Row className={styles.xia}>今日(kw.h)</Row>
            </Row>
            <Row className={[styles.energyBox, styles.yestodayBox].join(' ')}>
              <Row className={styles.row1}>{numberConversion(peakValue?.yestodayMax)}</Row>
              <Row className={styles.row2}>
                <p> {peakValue?.yestodayMaxTime || '--'}</p>
              </Row>
              <Row className={[styles.xia, styles.yestodayBgColor].join(' ')}>昨日(kw.h)</Row>
            </Row>
            <Row></Row>
          </Row>
        </Col>
      </Row>
      <Row gutter={[0, 24]}>
        <Col xl={10} lg={10} md={24} sm={24} xs={24}>
          <div className={styles.box} style={{ marginRight: 15, height: '100%' }}>
            <Row className={styles.sinTitle}>
              <span className={styles.signLine}></span>
              <span>环比</span>
            </Row>
            <Row gutter={24} style={{ margin: 0, marginBottom: '7px' }}>
              <Col xl={8} lg={8} md={8} sm={8} xs={8} className={styles.huanbiitem}>
                <p className={styles.number}>{numberConversion(energyNum.today_num || 0)}</p>
                <p className={styles.bt}>今日(kw.h)</p>
              </Col>
              <Col xl={8} lg={8} md={8} sm={8} xs={8} className={styles.huanbiitem}>
                <p className={styles.number}>{numberConversion(energyNum.yestoday_num || 0)}</p>
                <p className={styles.bt}>昨日(kw.h)</p>
              </Col>
              <Col xl={8} lg={8} md={8} sm={8} xs={8} className={styles.huanbiitem}>
                <div className={styles.qushiTop}>
                  <p>{energyNum.dayPercentage}</p>
                  <p className={styles.down}>{energyNum.dayDifference}</p>
                </div>
                <p className={styles.bt}>趋势</p>
              </Col>
            </Row>
            <Row gutter={24} style={{ margin: 0, marginBottom: '7px' }}>
              <Col xl={8} lg={8} md={8} sm={8} xs={8} className={styles.huanbiitem}>
                <p className={styles.number}>{numberConversion(energyNum.current_mouth_num || 0)}</p>
                <p className={styles.bt}>当月(kw.h)</p>
              </Col>
              <Col xl={8} lg={8} md={8} sm={8} xs={8} className={styles.huanbiitem}>
                <p className={styles.number}>{numberConversion(energyNum.last_mouth_num || 0)}</p>
                <p className={styles.bt}>上月(kw.h)</p>
              </Col>
              <Col xl={8} lg={8} md={8} sm={8} xs={8} className={styles.huanbiitem}>
                <div className={styles.qushiTop}>
                  <p>{energyNum.monthPercentage}</p>
                  <p className={styles.down}>{energyNum.monthDifference}</p>
                </div>
                <p className={styles.bt}>趋势</p>
              </Col>
            </Row>
            <Row gutter={24} style={{ margin: 0 }}>
              <Col xl={8} lg={8} md={8} sm={8} xs={8} className={styles.huanbiitem}>
                <p className={styles.number}>{numberConversion(energyNum.this_year_num || 0)}</p>
                <p className={styles.bt}>今年(kw.h)</p>
              </Col>
              <Col xl={8} lg={8} md={8} sm={8} xs={8} className={styles.huanbiitem}>
                <p className={styles.number}>{numberConversion(energyNum.last_year_num || 0)}</p>
                <p className={styles.bt}>去年(kw.h)</p>
              </Col>
              <Col xl={8} lg={8} md={8} sm={8} xs={8} className={styles.huanbiitem}>
                <div className={styles.qushiTop}>
                  <p>{energyNum.yearPercentage}</p>
                  <p className={styles.down}>{energyNum.yearDifference}</p>
                </div>
                <p className={styles.bt}>趋势</p>
              </Col>
            </Row>
          </div>
        </Col>
        <Col xl={14} lg={14} md={24} sm={24} xs={24} className={styles.box}>
          <Row className={styles.sinTitle}>
            <span className={styles.signLine}></span>
            <span>负荷趋势</span>
          </Row>
          <Row style={{ justifyContent: 'flex-end', marginTop: '-30px' }}>
            <Radio.Group
              value={{ type }}
              onChange={handleSizeChange}
              className={styles.qushiShanxuan}
            >
              <Radio.Button value="1" className={type == '1' ? styles.btnSelected : ''}>
                今日
              </Radio.Button>
              <Radio.Button value="2" className={type == '2' ? styles.btnSelected : ''}>
                本月
              </Radio.Button>
              <Radio.Button value="3" className={type == '3' ? styles.btnSelected : ''}>
                全年
              </Radio.Button>
            </Radio.Group>
          </Row>
          {qushiOption != null ? (
            <ECharts option={qushiOption} style={{ height: 400, width: '100%' }} />
          ) : null}
        </Col>
      </Row>
    </div>
  );
};

export default Survey;
